package pers.hl.module_main.mine

import android.os.Bundle
import android.text.TextUtils
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.TimeUtils
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import kotlinx.android.synthetic.main.item_rv_book.view.*
import pers.hl.common.base.ext.showMessage
import pers.hl.lib_global.common.GlideUtils
import pers.hl.lib_global.model.bean.Book
import pers.hl.lib_global.model.bean.BookBorRec
import pers.hl.lib_global.model.bean.BookShareRec
import pers.hl.lib_global.model.enums.BookStatus
import pers.hl.module_main.BaseTitleRvFragment
import pers.hl.module_main.R
import pers.hl.module_main.common.*

/**
 * 我的发布：只要发布的就属于这个
 */
class MyPublishFragment : BaseTitleRvFragment<BookShareRec>() {

    companion object {

        @JvmStatic
        fun newInstance(): MyPublishFragment {
            return MyPublishFragment()
        }
    }

    override fun getTitle(): String {
        return "我的发布"
    }

    override fun beforeSetAdapter() {
        createMenu()
    }

    private fun createMenu() {
        mBinding.apply {
            val creator = SwipeMenuHelper.createRightItem(mContext, "接受", "拒绝")
            recyclerView.setSwipeMenuCreator(creator)
            recyclerView.setOnItemMenuClickListener { menuBridge, adapterPosition ->

                // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
                menuBridge.closeMenu()
                val menuPos = menuBridge.position
                val item = mAdapter.getItem(adapterPosition)
                val data = item.borrowRecord
                if (data?.bbrStatus != Book.STATUS_BORROWING) {
                    showMessage("当前状态不可操作,status=${data?.bbrStatus}")
                    return@setOnItemMenuClickListener
                }
                ConfirmDialog.create(mContext)
                    .content(if (menuPos == 0) "您确定要接受借阅吗？" else "您确定要拒绝借阅吗")
                    .setConfirmListener {
                        when (menuPos) {
                            0 -> {
                                accept(data)
                            }
                            1 -> {
                                data.bbrId?.let {
                                    mViewModel.refuse(it).observe(this@MyPublishFragment, Observer {
                                        showMessage("拒绝成功")
                                        fetchMyPublish()
                                    })
                                }
                            }
                        }

                    }
                    .setCancelListener { }
                    .show()
            }
        }
    }

    private fun showBookQrCode(data: BookBorRec) {
        accept(data)
    }

    private fun accept(data: BookBorRec) {
        data.bbrId?.let {
            mViewModel.accept(it).observe(this@MyPublishFragment, Observer {
                showMessage("接受成功")
                fetchMyPublish()
            })
        }
    }

    override fun createAdapter(): BaseLibQuickAdapter<BookShareRec, BaseViewHolder> {
        return object : BaseLibQuickAdapter<BookShareRec, BaseViewHolder>(R.layout.item_rv_book) {
            override fun convert(holder: BaseViewHolder, item: BookShareRec) {
                val data = item.book
                val ivSearchBook = holder.itemView.ivSearchBook
                data?.apply {
                    GlideUtils.loadBookImage(ivSearchBook.context, ivSearchBook, data)
                    holder.itemView.tvBookName.text = data.bookName
                    val subTitle = String.format(
                        "%s", if (TextUtils.isEmpty(data.bookAuthor)) "佚名" else data.bookAuthor
                    )
                    holder.itemView.apply {
                        tvSearchSubtitle.text = subTitle
                        tvTime.text = TimeUtils.date2String(item.bsrCreateTime)
                        tvStatus.text = data.bookStatus?.let { getStatusName(it) }
                        setOnClickListener {
                            PageHelper.startBookDetailPage(mContext, data)
                        }
                    }
                }
            }
        }
    }

    private fun getStatusName(bookStatus: Int): String {
        return BookStatus.getValueStr(bookStatus)
    }

    override fun initData(savedInstanceState: Bundle?) {
        fetchMyPublish()
    }

    private fun fetchMyPublish() {
        mViewModel.fetchMyPublish().observe(this, Observer {
            if (it.isNullOrEmpty()) {
                mAdapter.setEmptyView()
            } else {
                mAdapter.setList(it)
                hideUnnecessaryMenu()
            }
        })
    }

    override fun hideUnnecessaryMenu() {
        val dataList = mAdapter.data
        dataList.forEachIndexed(action = { index, bookShareRec ->
            val book = bookShareRec.book
            if (book?.bookStatus != Book.STATUS_BORROWING) {
                hideMenu(index)
            }
        })
    }


}